from django.contrib.auth.models import AnonymousUser
from django.db.models import Q
from django.shortcuts import redirect
from django.urls import reverse
from django.utils.deprecation import MiddlewareMixin
from django.conf import settings
from django.utils.http import urlencode

from saas_main import models


class Tracer(object):

    def __init__(self):
        self.user = None
        self.price_policy = None
        self.project = None


class AuthMiddleware(MiddlewareMixin):

    def process_request(self, request):
        if request.method == 'GET' and isinstance(request.user, AnonymousUser) \
                and request.path_info not in settings.AUTH_WHITE_URL_LIST and not request.path_info.startswith('/static'):
            url = reverse('main:login')
            pre_page = request.get_full_path()
            return redirect(url+f'?{urlencode({"pre": pre_page})}')

    def process_view(self, request, callback, callback_args, callback_kwargs):
        tracer = Tracer()
        # callback视图函数名
        # callback_args位置传参
        # callback_kwargs关键字传参
        # 此方法在调用所有视图函数之前被调用
        if request.path_info.startswith("/manage"):
            pro_id = callback_kwargs.get('project')
            if projectrelation := models.ProjectRelation.objects.filter(
                    Q(user=request.user) & Q(project=pro_id)).first():
                request.tracer = tracer
                request.tracer.project = projectrelation.project
                return
            else:
                return redirect('main:project')
